package Controllers

import (
	"context"
	"fmt"
	"strconv"
	"work1/Config"
	"work1/DataBase"
	Model "work1/Models"
	service "work1/Service"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type TaskController struct {
	commonController
}

func (that *TaskController) ChangeStatus(request *gin.Context) {
	type validata struct {
		Id     int    `form:"id" binding:"required,number"`
		Status string `form:"status" binding:"required,oneof=0 1 2"`
	}
	var requestdata validata
	if err := request.ShouldBind(&requestdata); err != nil {
		that.SendFailResponse(request, err.Error())
		return
	}
	Task_model := Model.Task{}

	sessionModel := DataBase.DB.Begin()
	defer sessionModel.Rollback()
	TaskInfo := map[string]any{}
	err := sessionModel.Table(Task_model.TableName()).Where("id = ?", request.Request.FormValue("id")).Update("status", requestdata.Status).Find(&TaskInfo)
	if err.Error != nil {
		that.SendFailResponse(request, err.Error.Error())
		return
	}

	var changeDomainValue map[string]any
	//转香港服务器
	if requestdata.Status == "2" {
		DomainModel := Model.Domain{}
		DomainInfo := map[string]any{}
		sessionModel.Model(&DomainModel).Where("id = ?", TaskInfo["domain_id"]).Find(&DomainInfo)
		if len(DomainInfo) <= 0 {
			that.SendFailResponse(request, "域名信息不存")
			return
		}
		SshService := service.SshStruct{}
		AuthInfo := map[string]any{
			"ip_address": Config.Conf.Config.Hongkong.Host,
			"password":   Config.Conf.Config.Hongkong.Password,
			"name":       Config.Conf.Config.Hongkong.User,
			"type":       "password",
			"port":       Config.Conf.Config.Hongkong.Port,
		}
		changeDomainValue = map[string]any{}
		changeDomainValue["ip_addres"] = Config.Conf.Config.Hongkong.Host
		changeDomainValue["domain_id"] = fmt.Sprintf("%v", DomainInfo["id"])
		if status, err := SshService.Conn(AuthInfo, fmt.Sprintf("%v", AuthInfo["ip_address"])); !status {
			that.commonController.SendFailResponse(request, err)
			return
		}
		defer SshService.SshClient.Close()
		if err := new(ServerController).ConfigureServerSSL(&SshService, DomainInfo); err != nil {
			that.commonController.SendFailResponse(request, "转移至香港服务器失败"+fmt.Sprintf("%v", err))
			return
		}
	}
	sessionModel.Commit()
	fmt.Println(changeDomainValue)
	that.SendSuccessResponse(request, changeDomainValue, "")
}

func (con *TaskController) Index(request *gin.Context) {

	list_ch := make(chan map[string]interface{})

	Task_model := Model.Task{}
	server_model := Model.Server{}
	domain_model := Model.Domain{}

	var ctx context.Context
	BaseModel := DataBase.DB.Table(
		fmt.Sprintf("%v as t1", Task_model.TableName())).Joins(
		fmt.Sprintf("left join %v as t2", server_model.TableName()) + " on t2.id = t1.server_id").Joins(
		fmt.Sprintf("left join %v as t3", domain_model.TableName()) + " on t3.id = t1.domain_id").WithContext(ctx)

	go func(ch chan map[string]interface{}, request *gin.Context, BaseModel *gorm.DB) {

		pageSize, _ := strconv.Atoi(request.DefaultQuery("pageSize", "15"))
		page, _ := strconv.Atoi(request.DefaultQuery("page", "1"))
		page = (page - 1) * pageSize
		result := []map[string]any{}
		BaseModel.Select("t1.id as id,t2.name as server_name,concat_ws('.',t3.RR,t3.domain_name) as host,status").Limit(pageSize).Offset(page).Order("t1.id desc").Find(&result)

		data := map[string]any{}
		data["list"] = result
		data["page"], _ = strconv.Atoi(request.DefaultQuery("page", "1"))
		data["pageSize"] = pageSize

		ch <- data
		close(ch)
	}(list_ch, request, BaseModel)

	count_ch := make(chan any)

	go func(ch chan any, BaseModel *gorm.DB) {
		var count int64
		BaseModel.Count(&count)
		ch <- count
		close(ch)
	}(count_ch, BaseModel)

	data := <-list_ch
	data["count"] = <-count_ch

	con.SendSuccessResponse(request, &data, "")
}
